<template>
	<div :style="{ width: '100%', height: '100%' }">
		<div
			:id="containId"
			:style="{ width: containSize.width, height: containSize.height }"
			class="container"
		></div>
		<div class="map_search" :id="mapsearchId" v-if="detail !== 'detail'">
			<label id="tipinput_label" class="search_label"
			>地址查询:
			</label>
			<el-select
				v-model="tipinput"
				:id="tipinputId"
				ref="searchInput"
				filterable
				clearable class="search_input"
				remote
				reserve-keyword
				placeholder="请输入地址"
				:remote-method="remoteMethod"
				:loading="loading"
				@change="searchMarker"
				@clear="clearOptions"
			>
				<el-option
					v-for="item in options"
					:key="item.value"
					:label="item.label"
					:value="item.value"
				>
					<i-ep-search/>
					<span
						style="
          float: right;
          color: var(--el-text-color-secondary);
          font-size: 13px;
        "
					>{{ item.value }}</span
					>
				</el-option>
			</el-select>
			<!-- <el-button type="primary" class="mapbtn_sear" @click="addSearch" plain
			><i-ep-search />查询</el-button
		> -->
		</div>
		<el-button type="primary" class="mapbtn_promotion" @click="mapHide(true)" v-if="detail !== 'detail'" plain
		>
			<i-ep-promotion/>
			确认
		</el-button
		>
		<el-button type="danger" class="mapbtn_close" :style="{right: detail !== 'detail' ? '110px' : '20px'}" @click="mapHide(false)" plain
		>
			<i-ep-close/>
			{{ detail !== 'detail' ? '取消' : '关闭' }}
		</el-button
		>
	</div>
</template>

<script lang="ts" setup>
import iconMark from "@/assets/map/map-marker.png";

interface containSizeType {
	width: string;
	height: string;
}

let props = defineProps({
	containSize: {
		type: Object,
		default: () => ({width: "400px", height: "300px"}),
	},
	prevPoint: {
		type: Object,
		default: () => ({lat: 29.641156373429688, lng: 91.13585449304729}),
	},
	containId: {
		type: String,
		default: () => "contain",
	},
	detail: {
		type: String,
		default: () => '',
	}
});
let startPoint = Object.assign({},props.prevPoint);
let prevPoint = Object.assign({},props.prevPoint);
let tipinput = ref("");
const options = ref([]);
const loading = ref(false);

let currentPoint: {
	lat: Number;
	lng: Number;
};
let map; //地图
let marker; //点标记
let autoComplete;
let myIcon;
const tipinputId = ref(GenNonDuplicateID());
const mapsearchId = ref(GenNonDuplicateID());
const searchInput = ref();

const emit = defineEmits(["sendProjectPoint", "sendProjectAddr", "mapHide"]);

function GenNonDuplicateID() {
	let idStr = Date.now().toString(36)
	idStr += Math.random().toString(36).substr(3)
	return idStr
}

onMounted(() => {
	currentPoint = prevPoint;
	init();
});

onUnmounted(() => {
	destroyMap();
});

function remoteMethod(query) {
	if(query){
		loading.value = true;
		// autoComplete.setInputValue(query);
		autoComplete.search(query)
	}
}

function searchFun() {
	var results = autoComplete.getResults(); //获取第一个智能搜索的结果
	let tempRs = results._pois.map(item => {
		return {
			label: item.province +
				item.city +
				item.district +
				item.street +
				item.business,
			value: item.province +
				item.city +
				item.district +
				item.street +
				item.business,
		}
	})
	
	loading.value = false;
	options.value = tempRs;
}

function searchMarker(val){
	if(val){
		map.clearOverlays(); //清除地图上所有覆盖物
		function myFun() {
			var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
			emit("sendProjectPoint", pp);
			emit("sendProjectAddr", val);
			map.centerAndZoom(pp, 18);
			map.addOverlay(new BMapGL.Marker(pp, {icon: myIcon})); //添加标注
		}
		
		var local = new BMapGL.LocalSearch(map, {
			//智能搜索
			onSearchComplete: myFun,
		});
		local.search(val);
	}
}

function clearOptions() {
	options.value = [];
}

function mapHide(choose) {
	clearOptions();
	if(!choose){
		emit("sendProjectPoint", startPoint);
		emit("sendProjectAddr", '');
	}
	emit("mapHide",choose);
}

function destroyMap() {
	clearMarker();
	tipinput.value = '';
	if (autoComplete) {
		autoComplete.hide();
		autoComplete.dispose();
		autoComplete = null;
	}
	if (map) {
		map.destroy();
		map = null;
	}
}

async function init() {
	/* 注册map */
	map = new BMapGL.Map(props.containId);
	let point = new BMapGL.Point(currentPoint.lng, currentPoint.lat);
	map.centerAndZoom(point, 13);
	map.enableScrollWheelZoom(true);
	// 添加比例尺控件
	var scaleCtrl = new window.BMapGL.ScaleControl();
	map.addControl(scaleCtrl);
	// 添加缩放控件
	var zoomCtrl = new window.BMapGL.ZoomControl();
	map.addControl(zoomCtrl);
	// 添加城市列表控件
	var cityCtrl = new window.BMapGL.CityListControl();
	map.addControl(cityCtrl);
	
	/* 注册单击事件 */
	map.addEventListener("click", getLatLng);
}

function G(id) {
	return document.getElementById(id);
}

async function searchAddress() {
	searchInput.value.$refs.reference.ref.id = GenNonDuplicateID();
	
	if (!autoComplete) {
		autoComplete = new BMapGL.Autocomplete({
			//建立一个自动完成的对象
			input: `${searchInput.value.$refs.reference.ref.id}`,
			// input: 'tipinputId',
			location: map,
			onSearchComplete: searchFun,
		});
	}
}

/* 地图点击事件 */
function getLatLng(point) {
	if(props.detail === 'detail'){
		return;
	}
	
	currentPoint.lat = point.latlng.lat;
	currentPoint.lng = point.latlng.lng;
	addMarker(currentPoint);
	emit("sendProjectPoint", currentPoint);
}

/* 添加点标记 */
function addMarker(point) {
	clearMarker();
	
	var gc = new BMapGL.Geocoder();
	var new_point = new BMapGL.Point(currentPoint.lng, currentPoint.lat);
	gc.getLocation(new_point, function (rs) {
		var addComp = rs.addressComponents;
		// //获取详细的地址，精确到街道的名称
		var addrname =
			addComp.city + addComp.district + addComp.street + addComp.streetNumber;
		emit("sendProjectAddr", addrname);
	});
	if (BMapGL) {
		myIcon = new BMapGL.Icon(iconMark, new BMapGL.Size(36, 36), {
			// 指定定位位置。
			// 当标注显示在地图上时，其所指向的地理位置距离图标左上
			// 角各偏移10像素和25像素。您可以看到在本例中该位置即是
			// 图标中央下端的尖角位置。
			// anchor: new BMapGL.Size(45, 45),
			// 设置图片偏移。
			// 当您需要从一幅较大的图片中截取某部分作为标注图标时，您
			// 需要指定大图的偏移位置，此做法与css sprites技术类似。
			// imageOffset: new BMapGL.Size(0, 0 - 25)   // 设置图片偏移
		});
		// 创建标注对象并添加到地图
		marker = new BMapGL.Marker(point, {icon: myIcon});
		map.addOverlay(marker);
	}
}

// 设置中心点
function setCenter(point) {
	if (map) {
		startPoint = Object.assign({},point);
		
		if(props.detail === 'detail'){
			map.centerAndZoom(point, 18);
		}else {
			map.centerAndZoom(point, 13);
		}
	}
}

// 清除 marker
function clearMarker() {
	if (marker) marker.remove();
	if (map) map.clearOverlays();
}

function clearMap() {
	map.removeEventListener("click", getLatLng);
}

defineExpose({
	destroyMap,
	addMarker,
	setCenter,
	searchAddress,
	init,
});
</script>

<style lang="scss" scoped>
.container {
	position: relative;
	margin: 35px 20px 35px 20px;
	border-radius: 10px;
	z-index: 0;
}

.search_input {
	width: 200px;
	height: 22px;
	line-height: 22px;
	// border: 1px solid #a5a5a5 !important;
	font-size: 13px;
	color: #181818;
	z-index: 9999;
}

:deep() .el-select .el-input {
	width: 200px;
	height: 22px;
	line-height: 22px;
	font-size: 13px;
	color: #181818;
}

.search_label {
	width: 120px;
	font-size: 12px;
	color: #797878;
}

.map_search {
	position: absolute;
	top: 10px;
	left: 20px;
	width: 100%;
	z-index: 9999;
}

.tangram-suggestion-main {
	z-index: 9999;
}

.mapbtn_sear {
	height: 22px;
	line-height: 22px;
	font-size: 13px;
	margin-left: 5px;
}

.mapbtn_close {
	height: 32px;
	line-height: 32px;
	font-size: 13px;
	position: absolute;
	right: 110px;
	bottom: 0px;
}

.mapbtn_promotion {
	height: 32px;
	line-height: 32px;
	font-size: 13px;
	position: absolute;
	right: 20px;
	bottom: 0px;
}
</style>
